package com.slkj.shilixiaoyuanapp.ui.parent.tool.activities;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.slkj.shilixiaoyuanapp.BuildConfig;
import com.slkj.shilixiaoyuanapp.R;
import com.slkj.shilixiaoyuanapp.base.ActivityInfo;
import com.slkj.shilixiaoyuanapp.base.BaseActivity;
import com.slkj.shilixiaoyuanapp.data.LeaveTypeData;
import com.slkj.shilixiaoyuanapp.data.UserRequest;
import com.slkj.shilixiaoyuanapp.entity.BasePickerTypeEntity;
import com.slkj.shilixiaoyuanapp.entity.PeopleEntity;
import com.slkj.shilixiaoyuanapp.entity.UserEntity;
import com.slkj.shilixiaoyuanapp.entity.code.ToolCode;
import com.slkj.shilixiaoyuanapp.entity.code.UiCode;
import com.slkj.shilixiaoyuanapp.entity.parent.BodyartspecialtyEntity;
import com.slkj.shilixiaoyuanapp.net.CommonResult;
import com.slkj.shilixiaoyuanapp.net.HttpHeper;
import com.slkj.shilixiaoyuanapp.net.callback.BaseFunctionCallBack;
import com.slkj.shilixiaoyuanapp.net.callback.CommonCallBack;
import com.slkj.shilixiaoyuanapp.ui.common.ChoseAuditorActivity__JumpCenter;
import com.slkj.shilixiaoyuanapp.ui.common.adapter.ChosePicAdapter;
import com.slkj.shilixiaoyuanapp.ui.parent.tool.common.CommonToolHistoryActivity__JumpCenter;
import com.slkj.shilixiaoyuanapp.util.StringUtils;
import com.slkj.shilixiaoyuanapp.util.TimeUtils;
import com.slkj.shilixiaoyuanapp.util.UpdataFileUtil;
import com.slkj.shilixiaoyuanapp.util.picture.FileUtils;
import com.slkj.shilixiaoyuanapp.util.picture.TakePictureUtils;
import com.slkj.shilixiaoyuanapp.view.DialogProvider;
import com.slkj.shilixiaoyuanapp.view.NumberEditText;
import com.slkj.shilixiaoyuanapp.view.PickerViewProvider;
import com.slkj.shilixiaoyuanapp.view.dialog.LoadSuccessAndFailDialog;
import com.tkk.api.RxEventProcessor;
import com.tkk.api.annotation.Recipient;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.ObservableSource;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.RuntimePermissions;
import static com.slkj.shilixiaoyuanapp.entity.code.RxEventProcessorTag.CHOSE_SPR_FINSH;
import static com.slkj.shilixiaoyuanapp.entity.code.UiCode.CHOSE_PIC_MAX_SIZW;
import static com.slkj.shilixiaoyuanapp.entity.code.UiCode.CHOSE_PIC_SPAN_COUNT;
import static com.slkj.shilixiaoyuanapp.entity.code.UiCode.NO_CHOSE;

@RuntimePermissions
@ActivityInfo(layout = R.layout.activity_activitys,title = "校外活动",rightHint = "历史记录")
public class ActivitysActivity extends BaseActivity {
    private int qjTypeId = NO_CHOSE;
    @BindView(R.id.tv_student_name)
    TextView tv_student_name;
    @BindView(R.id.et_act_name)
    EditText et_act_name;
    @BindView(R.id.edit_act_place)
    EditText edit_act_place;
    @BindView(R.id.et_act_time)
    EditText et_act_time;
    @BindView(R.id.tv_act_time)
    TextView tv_act_time;
    @BindView(R.id.tv_act_type)
    TextView tv_act_type;
    @BindView(R.id.edit_content)
    NumberEditText edit_content;
    @BindView(R.id.recyc_pic)
    RecyclerView recyc_pic;
    String time;
    @BindView(R.id.tv_spr)
    TextView tvSpr;
    List<Integer> sqrIds = new ArrayList<>();
    private ArrayList<BodyartspecialtyEntity.AuditorEntity> peopleEntities = new ArrayList<>();
    public static final String tag = "ActivitysActivity";
    private ArrayList<String> picPaths = new ArrayList<>();
    public TakePictureUtils takePictureUtils;
    ChosePicAdapter adapter;
    //班级id
    private int classId = NO_CHOSE;
    //学生id
    private int studentId = NO_CHOSE;

    @Override
    protected void init() {
        for (int i=0;i<UserRequest.getInstance().getUser().getStudents().size();i++){
            if (UserRequest.getInstance().getUser().getStudents().get(i).getIsSelect()==1){
                studentId=UserRequest.getInstance().getUser().getStudents().get(i).getId();
                classId=UserRequest.getInstance().getUser().getStudents().get(i).getClassId();
                tv_student_name.setText(UserRequest.getInstance().getUser().getStudents().get(i).getName());
            }
        }
//        if (UserRequest.getInstance().getUser().getStudents().size()!=0) {
//            tv_student_name.setText(UserRequest.getInstance().getUser().getStudents().get(0).getName());
//        }
        RxEventProcessor.get().bind(this);
        recyc_pic.setLayoutManager(new GridLayoutManager(this, CHOSE_PIC_SPAN_COUNT));
        adapter = new ChosePicAdapter(picPaths, this);
        recyc_pic.setAdapter(adapter);
        takePictureUtils = TakePictureUtils.Builder.from(this).isCompressor(false).isTailor(false).creat();
        takePictureUtils.setTakeCallBacklistener(new TakePictureUtils.TakePictureListener() {
            @Override
            public void successful(File outFile) {
                picPaths.add(outFile.getPath());
                adapter.notifyItemInserted(picPaths.size());
            }

            @Override
            public void failed(int errorCode, List<String> deniedPermissions) {
            }
        });
    }

    @Override
    protected void onRightTitleClick() {
        CommonToolHistoryActivity__JumpCenter.builder(this)
                .setNetToolType(14)
                .setToolType(ToolCode.P_TOOL_XYHD)
                .create().go();
    }

//    /**
//     * 选择学生
//     */
//    @OnClick(R.id.rl_select_student)
//    public void onLayoutChooseStudent() {
//        List<UserEntity.StudentEntity> students = UserRequest.getInstance().getUser().getStudents();
//        PickerViewProvider.getCommonPicker(this, students, new OnOptionsSelectListener() {
//            @Override
//            public void onOptionsSelect(int options1, int options2, int options3, View v) {
//                tv_student_name.setText(students.get(options1).getName());
//                studentId = students.get(options1).getId();
//                classId  = students.get(options1).getClassId();
//            }
//        }).show();
//    }

    @OnClick(R.id.layout_choose_acttype)
    public void onLayoutChooseActType(){
        List<BasePickerTypeEntity> typeEntityList = LeaveTypeData.getInstance().getParentActType();
        PickerViewProvider.getCommonPicker(this, typeEntityList, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                tv_act_type.setText(typeEntityList.get(options1).getName());
                qjTypeId = options1 + 1;
            }
        }).show();
    }

    @OnClick(R.id.layout_choose_acttime)
    public void onLayoutChooseWinTime(){
        PickerViewProvider.getTimePicker(this, (date, v) -> {
            time = TimeUtils.dateToStrM(date);
            tv_act_time.setText(time);
        },new boolean[]{true, true, true, false, false, false}).show();
    }

    @OnClick(R.id.tv_up)
    void commit(){
        String actName=et_act_name.getText().toString();
        String actTime=et_act_time.getText().toString();
        String actPlace=edit_act_place.getText().toString();
        String actTime1=tv_act_time.getText().toString();
        String actType=tv_act_type.getText().toString();
        String content=edit_content.getText().toString();
        if (studentId == NO_CHOSE) {
            showToast("请选择学生");
            return;
        }
        if (TextUtils.isEmpty(actName)){
            showToast("请输入活动名称");
            return;
        }
        if (TextUtils.isEmpty(actPlace)){
            showToast("请输入活动地点");
            return;
        }
        if (TextUtils.isEmpty(actTime)){
            showToast("请输入活动时长");
            return;
        }
        if (TextUtils.isEmpty(actTime1)){
            showToast("请选择活动时间");
            return;
        }
        if (TextUtils.isEmpty(actType)){
            showToast("请选择活动类别");
            return;
        }
        if (sqrIds.size() == 0) {
            showToast("请选择审批人");
            return;
        }
        UpdataFileUtil.UpImgObservable("award", picPaths)
                .flatMap(new BaseFunctionCallBack<List<String>, String>() {
                    @Override
                    public ObservableSource<CommonResult<String>> back(List<String> result) {
                        String img = StringUtils.listToString(result);
                        //int classId=UserRequest.getInstance().getUser().getClassX().get(0).getClassId();
                        String body=edit_content.getText();
                        return HttpHeper.get().parentService().addSchoolActivitys(studentId,actName,actPlace, actTime1, qjTypeId, content,img,Double.parseDouble(actTime),sqrIds.toString());
                    }
                })
                .compose(getThread())
                .compose(bindToLifecycle())
                .subscribe(new CommonCallBack<String>(true, this) {
                    @Override
                    public void onCallBackSuccess(String data) {
                        LoadSuccessAndFailDialog.showSuccess(ActivitysActivity.this,data);
                        clearContent();
                    }
                });

    }

    @Recipient(tag = tag + CHOSE_SPR_FINSH)
    void onChoseObjFinsh(int code, String info, List<BodyartspecialtyEntity.AuditorEntity> peopleEntityList, List<Integer> checkIds) {
        tvSpr.setText(checkIds.size() == 0 ? "" : info);
        sqrIds.clear();
        sqrIds.addAll(checkIds);
        peopleEntities.clear();
        peopleEntities.addAll(peopleEntityList);
    }

    @OnClick(R.id.layout_chose_pic)
    void chosePic() {
        if (picPaths.size() == CHOSE_PIC_MAX_SIZW) {
            showToast("最多添加" + CHOSE_PIC_MAX_SIZW + "张图片");
            return;
        }
        DialogProvider.getPhotoDialog(this, new DialogProvider.TakePicTypeListener() {
            @Override
            public void takePhoto() {
                takePictureUtils.getByCarema();
            }

            @Override
            public void chosePhoto() {
                ActivitysActivityPermissionsDispatcher.onAgreePermissionWithPermissionCheck(ActivitysActivity.this);
            }
        });

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        takePictureUtils.attachToActivityForResult(requestCode, resultCode, data);
        if (requestCode == UiCode.CHOSE_PIC_CODE && resultCode == RESULT_OK) {
            List<Uri> mSelected = Matisse.obtainResult(data);
            for (int i = 0; i < mSelected.size(); i++) {
                String filePath = FileUtils.getPathByUri(this, mSelected.get(i));
                picPaths.add(filePath);
            }
            adapter.notifyItemRangeInserted(picPaths.size(), mSelected.size());
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        takePictureUtils.onRequestPermissionsResult(requestCode, permissions, grantResults);
        ActivitysActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @NeedsPermission({Manifest.permission.CAMERA})
    void onAgreePermission() {
        Matisse.from(this)
                .choose(MimeType.ofImage())
                .countable(true)
                .maxSelectable(CHOSE_PIC_MAX_SIZW - picPaths.size())
                .captureStrategy(new CaptureStrategy(true, BuildConfig.APPLICATION_ID + ".fileprovider"))
                .imageEngine(new GlideEngine())
                .forResult(UiCode.CHOSE_PIC_CODE);
    }

    @OnPermissionDenied({Manifest.permission.CAMERA})
    void onDeniedPermission() {
        showToast("读取照片权限获取失败");
    }

    @OnClick(R.id.layout_chose_spr)
    public void onLayoutChoseSprClicked() {
        if (peopleEntities.size() == 0) {
            HttpHeper.get().parentService().getBodyartspecialty()
                    .compose(bindToLifecycle())
                    .compose(getThread())
                    .subscribe(new CommonCallBack<BodyartspecialtyEntity>(true, this) {
                        @Override
                        public void onCallBackSuccess(BodyartspecialtyEntity data) {
                            peopleEntities.addAll(data.getAuditor());
                            ChoseAuditorActivity__JumpCenter.builder(ActivitysActivity.this).setTag(tag).setData(peopleEntities).create().go();
                        }
                    });
        } else {
            ChoseAuditorActivity__JumpCenter.builder(ActivitysActivity.this).setTag(tag).setData(peopleEntities).create().go();

        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RxEventProcessor.get().unBind(this);
    }
}
